package com.zx.zxpicture.infrstructure.manager;

import cn.hutool.core.io.FileUtil;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.exception.CosServiceException;
import com.qcloud.cos.model.*;
import com.qcloud.cos.model.ciModel.persistence.PicOperations;
import com.zx.zxpicture.infrstructure.common.ErrorCode;
import com.zx.zxpicture.infrstructure.config.CosClientConfig;
import java.io.File;
import java.util.ArrayList;
import javax.annotation.Resource;

import com.zx.zxpicture.infrstructure.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * 通用类
 * Cos 对象存储操作
 * @author <a href="https://github.com/liyupi">程序员鱼皮</a>
 * @from <a href="https://yupi.icu">编程导航知识星球</a>
 */
@Component
@Slf4j
public class CosManager {
    @Resource
    private CosClientConfig cosClientConfig;
    @Resource
    private COSClient cosClient;

    /**
     * 文件上传（只有文件上传功能）
     * （拿不到上传的文件的信息！！！！）
     *
     * @param key  文件在桶中存储路径
     * @param file 要存储的文件
     * @return 返回null
     */
    public PutObjectResult putObject(String key, File file) {
        // 指定文件将要存放的存储桶
        String bucketName = cosClientConfig.getBucket();
        //构造上传请求参数
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, file);
        PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
        return putObjectResult;
    }

    /**
     * 下载文件
     *
     * @param key 文件路径
     * @return 文件对象（可以通过这个对象获取到它的输入流）
     */
    public COSObject getObject(String key) {
        GetObjectRequest getObjectRequest = new GetObjectRequest(cosClientConfig.getBucket(), key);
        // 获取文件对象
        return cosClient.getObject(getObjectRequest);
    }

    /**
     * 上传对象（返回上传的图片信息）
     * @param key  文件路径（包括文件名）
     * @param file 文件
     */
    public PutObjectResult putPictureObject(String key, File file) {
        PutObjectRequest putObjectRequest = new PutObjectRequest(cosClientConfig.getBucket(), key,
                file);
        // 对图片进行处理（获取基本信息也被视作为一种处理）
        PicOperations picOperations = new PicOperations();
        // 1 表示返回原图信息
        picOperations.setIsPicInfo(1);
        ArrayList<PicOperations.Rule> rules = new ArrayList<>();
        //1.图片压缩（转成 webp 格式）
        //自定义文件名
        String webpKey = FileUtil.mainName(key) + ".webp"; //mainName方法是拿不到文件后缀的
        PicOperations.Rule rule = new PicOperations.Rule();
        rule.setFileId(webpKey);
        rule.setBucket(cosClientConfig.getBucket());
        //转换图片格式为webp
        rule.setRule("imageMogr2/format/webp");
        // 构造处理参数
        rules.add(rule);
        //2.图片缩放
        //如果原图片太小，就不进行缩略
        if(file.length() > 2 * 1024){
            String thumbnailKey = FileUtil.mainName(key)+"_thumbnail." + FileUtil.getSuffix(key); //mainName方法是拿不到文件后缀的
            PicOperations.Rule thumbnailRule = new PicOperations.Rule();
            thumbnailRule.setFileId(thumbnailKey);
            thumbnailRule.setBucket(cosClientConfig.getBucket());
            //转换图片格式为webp
            thumbnailRule.setRule(String.format("imageMogr2/thumbnail/%sx%s>", 256, 256));//缩放为256x256 px
            // 构造处理参数
            rules.add(thumbnailRule);
        }
        picOperations.setRules(rules);
        putObjectRequest.setPicOperations(picOperations);
        return cosClient.putObject(putObjectRequest);
    }

    /**
     * 删除对象
     * @param key 图片路径（唯一标识）
     * @throws CosClientException
     * @throws CosServiceException
     */
    public void deleteObject(String key) {
        try {
            cosClient.deleteObject(cosClientConfig.getBucket(), key);
        }catch (Exception e){
            log.error("删除对象失败", e);
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "删除对象失败");
        }
    }
}
